<template>
    <div>
        <Meta-Dialog v-model="isShow" width="527">
            <template #header
                ><div>
                    {{ isMerge ? '编辑合并问题' : '新增体检结果' }}
                </div>
            </template>

            <MetaForm
                :formData="formData"
                :formColumn="formColumn"
                :labelWidth="80"
                labelPosition="left"
                class="mx-[7px] mt-[10px] -mb-[10px]"
            >
                <template #LabelName>
                    <el-form-item label="体检结果">
                        <template v-if="formData.IsManually === 1">
                            <jrInput
                                v-model="formData.LabelName"
                                :style="
                                    isMerge ? 'width: 100%' : 'width: 180px'
                                "
                            ></jrInput>
                        </template>
                        <template v-else>
                            <JrSelectRemote
                                :formData="formData"
                                prop="InstanceID"
                                searchType="tjxmgz"
                                style="width: 180px"
                                placeholder="请输入查询选择"
                                :onChange="doChangeInstanceID"
                            ></JrSelectRemote>
                        </template>

                        <JrRadio
                            v-if="!isMerge"
                            :formData="formData"
                            prop="IsManually"
                            :options="radioOptions"
                            class="ml-[20px]"
                            :onInput="onInputIsManually"
                        ></JrRadio>
                    </el-form-item>
                </template>
            </MetaForm>

            <div class="flex justify-end mt-[10px] mb-[5px] px-[7px]">
                <el-button size="small" @click="close">取消</el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="doSave"
                    :loading="saveLoading"
                    >保存</el-button
                >
            </div>
        </Meta-Dialog>
    </div>
</template>

<script setup>
import {
    QueryHealthCheckupProjectDetailAsyncApi,
    SaveKnowledgeItemDataAsyncApi
} from '@/api/home'
import JrSelectRemote from '@/components/MetaForm/JrSelectRemote.vue'
import { useLoadingStore } from '@/stores/loading'
import { ElMessage } from 'element-plus'
import { inject, reactive, ref } from 'vue'

const isShow = ref(false)
const isMerge = ref(false)
const saveLoading = ref(false)
const zhinengtijianData = inject('zhinengtijianData')
const formData = ref({})

const radioOptions = [
    {
        value: 0,
        label: '规则库选择'
    },
    {
        value: 1,
        label: '手动编辑'
    }
]

const loadingStore = useLoadingStore()

const getZhiJjianDetail = inject('getZhiJjianDetail')
const newData = {
    OperationType: 1, // 0编辑  1新增
    IsManually: 0, // 是否手动编辑  0下拉框选择  1手工填写
    KnowledgeItemID: 0, // 体检报告明细ID（编辑时传入，新增可为0）
    InstanceID: '', // 标签实例ID（唯一标识一个结论项）
    LabelName: '', // 标签名称（如：高胆固醇、甲状腺结节）
    LabelValue: '', // 标签值（检测值+单位，如：6.8 mmol/L）
    HealthAdvice: '',
    Reason: '',
    OldIDs: '' // 合并时，旧ID，逗号分割
}

const formColumn = reactive([
    {
        prop: 'LabelName',
        label: '体检结果',
        slot: 'LabelName',
        span: 24
    },
    {
        prop: 'HealthAdvice',
        label: '健康建议',
        componentName: 'input',
        type: 'textarea',
        istrim: false,
        span: 24
    },
    {
        prop: 'Reason',
        label: '判断依据',
        componentName: 'input',
        type: 'textarea',
        istrim: false,
        span: 24
    }
])

const open = (data) => {
    isMerge.value = data.isMerge
    if (data.isMerge) {
        const { Reason, HealthAdvice, OldIDs, isMerge } = data
        formData.value = Object.assign({}, newData, {
            ...data,
            IsManually: 1,
            Reason,
            HealthAdvice,
            OldIDs
        })
    } else {
        formData.value = Object.assign({}, newData)
    }
    isShow.value = true
}

const close = () => {
    isShow.value = false
}

// 根据id获取项目规则详情
const getProjectDetail = (projectID) => {
    loadingStore.showFullLoading = true
    QueryHealthCheckupProjectDetailAsyncApi({
        projectID
    })
        .then((res) => {
            loadingStore.showFullLoading = false
            if (res?.Code == '200') {
                formData.value = {
                    ...formData.value,
                    ...res.Data,
                    LabelName: res.Data.ProjectName
                }
            } else {
                ElMessage.error(res?.Message || '获取项目规则详情失败')
            }
        })
        .catch((e) => {
            loadingStore.showFullLoading = false
            console.log(e)
        })
}

const onInputIsManually = () => {
    if (formData.value.IsManually) {
        formData.value.InstanceID = ''
    }
}

const doChangeInstanceID = () => {
    if (formData.value.InstanceID) {
        getProjectDetail(formData.value.InstanceID)
    }
}

// 编辑保存检查明细
const doSave = () => {
    if (formData.value.IsManually == 1 && !formData.value.LabelName) {
        ElMessage.error('请完成体检结果未填内容')
        return
    }
    if (formData.value.IsManually == 0 && !formData.value.InstanceID) {
        ElMessage.error('请完成体检结果未填内容')
        return
    }
    if (!formData.value.HealthAdvice || !formData.value.Reason) {
        ElMessage.error('请完成体检结果未填内容')
        return
    }
    saveLoading.value = true
    const data = {
        ...formData.value,
        HealthCheckupID: zhinengtijianData.value.HealthCheckupID, // 体检ID（关联体检记录）
        KnowledgeID: zhinengtijianData.value.KnowledgeID, // 体检报告ID（知识库主表ID）
        VersionID: zhinengtijianData.value.VersionID // 版本ID（用于版本控制）
    }
    SaveKnowledgeItemDataAsyncApi(data)
        .then((res) => {
            saveLoading.value = false
            if (res?.Code == '200') {
                ElMessage.success('修改完成')
                close()
                getZhiJjianDetail()
            } else {
                ElMessage.error(res.Message)
            }
        })
        .catch((e) => {
            console.log(e)
            saveLoading.value = false
        })
}

defineExpose({
    open
})
</script>

<style scoped lang="scss"></style>
